<?php
class FTP {
	private $docroot;//Example : /home/jatinder/public_html/
	private $ftproot; //Example : /public_html/
	private $host;
	private $username;
	private $password;
	private $ftpstream;
	public $debug;
	

	public function FTP($docroot, $ftproot, $host, $username, $password) {
		$this->docroot = $docroot;
		$this->ftproot = $ftproot;
		$this->host = $host;
		$this->username = $username;
		$this->password = $password;
		
		$ftpstream = @ftp_connect($host);
		if($ftpstream) {
			$login = @ftp_login($ftpstream, $username, $password);
			if($login) {
				$this->ftpstream = $ftpstream;
				return true;
			} else {
				$this->debug = "Failed to login to FTP server! (Username or password)<br />";
				@ftp_close($ftpstream);
				return false;
			}
		} else {
			$this->debug = "Failed to connect to FTP server! (HOST)<br />";
			return false;
		}
	}
	
	public function mkdir($pathname) {
		if($this->ftpstream)
			ftp_mkdir($this->ftpstream, $this->ftproot.$pathname);
		else
			return false;
	}
	
	public function fopen($filename) {
		if($this->ftpstream) {
			$file = basename($filename);
			$temp = tmpfile();
			@ftp_fput($this->ftpstream, $this->ftproot.$filename, $temp, FTP_ASCII);
			fclose($temp);
			return true;
		} else {
			return false;
		}
	}
	
	public function fputs($filename, $mode, $data) {
		if($this->ftpstream) {
			@ftp_site($this->ftpstream,"CHMOD 0777 ".$this->ftproot.$filename);
			$fp = fopen($this->docroot.$filename, $mode);

			fputs($fp,$data);

			fclose($fp);

			@ftp_site($this->ftpstream,"CHMOD 0644 ".$this->ftproot.$filename);
			return true;
		} else {
			return false;
		}
	}
	
	public function cleanup() {
		if($this->ftpstream) {
			ftp_close($this->ftpstream);
			return true;
		} else {
			return false;
		}
	}
}
?>
